package cn.lzg.server.module.user.service;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.lzg.common.core.exception.ErrorCodeException;
import cn.lzg.common.core.model.ResultCode;
import cn.lzg.common.core.session.Session;
import cn.lzg.common.core.session.SessionManager;
import cn.lzg.common.module.user.response.Image;
import cn.lzg.common.module.user.response.UserResponse;
import cn.lzg.server.module.user.dao.UserDao;
import cn.lzg.server.module.user.entity.User;

@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userdao;

	@Override
	public UserResponse login(Session session, String userId, String password) {
		UserResponse response = null;
		System.out.println("登陆：" + userId + " " + password);
		// 是否重新登陆
		if (session.getAttachment() != null) {
			throw new ErrorCodeException(ResultCode.HAS_LOGIN);
		}

		User existUser = userdao.findUserById(userId);
		// 用户不存在
		if (existUser == null) {
			System.out.println("existUser == null");
			throw new ErrorCodeException(ResultCode.USER_NO_EXIST);
		}

		// 密码错误
		if (!existUser.getPassword().equals(password)) {
			System.out.println("密码错误");
			throw new ErrorCodeException(ResultCode.PASSWORD_ERROR);
		}
		/**
		 * 抢登陆
		 */
		if (SessionManager.isUserOnline(existUser.getUserId())) {
			System.out.println("抢登陆");
			Session oldSession = SessionManager.removeSession(existUser.getUserId());
			// 解绑用户
			oldSession.removeAttachment();
			// 踢用户下线
			oldSession.close();
		}

		/**
		 * 保存Session到会话管理器
		 */
		if (SessionManager.putSession(existUser.getUserId(), session)) {
			System.out.println("保存Session到会话管理器");
			// 绑定
			session.setAttachment(existUser);
		} else {
			throw new ErrorCodeException(ResultCode.LOGIN_FAIL);
		}
		/**
		 * 查找数据库，封装联系人信息 头像，id，用户名
		 */
		Image avatar = null;
		if (existUser.getPhoto() != null) {
			System.out.println("目录");
			File file = new File(existUser.getPhoto());
			try {
				System.out.println("读取图片中");
				avatar = new Image();
				byte[] data = FileUtils.readFileToByteArray(file);
				avatar.setFilename(existUser.getPhoto());
				avatar.setData(data);
			} catch (IOException e) {
				System.out.println("读取图片失败");
				e.printStackTrace();
			}
		}

		/**
		 * 查找数据库，封装群组信息
		 */

		/**
		 * 离线消息处理
		 */

		// private String userId;
		// private String username;
		// private String password;
		// private String sex;
		// private String adress;
		// private String trades;
		// private byte[] avatar;
		// 响应
		response = new UserResponse();
		response.setUserId(existUser.getUserId());
		response.setUsername(existUser.getUsername());
		response.setPassword(existUser.getPassword());
		response.setSex(existUser.getSex());
		response.setAdress(existUser.getAdress());
		response.setTrades(existUser.getTrades());
		response.setAvatar(avatar);
		return response;
	}

	@Override
	public UserResponse register(Session session, String id, String password) {
		UserResponse response = null;

		User existUser = userdao.findUserById(id);
		// 客户存在
		if (existUser != null) {
			throw new ErrorCodeException(ResultCode.USER_EXIST);
		}

		// 保存用户到数据库
		existUser = new User();
		existUser.setUserId(id);
		existUser.setPassword(password);
		userdao.addUser(existUser);

		// 响应
		response = new UserResponse();
		response.setUserId(existUser.getUserId());
		response.setPassword(existUser.getPassword());

		return response;
	}

}
